package com.franklions.casdoor.example.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.franklions.casdoor.example.config.AppConfigProperties;
import com.franklions.casdoor.example.context.SecurityContextHolder;
import com.franklions.casdoor.example.exception.ErrorCode;
import com.franklions.casdoor.example.exception.ErrorResult;
import org.casbin.casdoor.entity.User;
import org.casbin.casdoor.exception.AuthException;
import org.casbin.casdoor.service.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Administrator
 * @version 1.0
 * @date 2020/2/2
 * @since Jdk 1.8
 */
public class JwtTokenAuthorizeFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtTokenAuthorizeFilter.class);
    private PathMatcher pathMatcher = new AntPathMatcher();
    private AppConfigProperties properties;
    private ObjectMapper objectMapper;
    private AuthService accessTokenService;

    public JwtTokenAuthorizeFilter(AppConfigProperties properties, AuthService tokenService, ObjectMapper objectMapper) {
        this.properties = properties;
        this.objectMapper = objectMapper;
        this.accessTokenService = tokenService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String uri = request.getRequestURI();
            String method = request.getMethod();

            if("OPTIONS".equalsIgnoreCase(method)){
                filterChain.doFilter(request, response);
                return;
            }

            String path = request.getRequestURI();
            if(matchesIgnoredPatterns(path)){
                logger.info("ignored url,"+path);
                filterChain.doFilter(request, response);
                return;
            }

            logger.info("web auth url,"+path);

            /**/
            //TODO 权限验证过程
            // get authorization header and validate
            final String header = request.getHeader(HttpHeaders.AUTHORIZATION);
            if (!StringUtils.hasText(header) || !header.startsWith("Bearer ")) {
                responseErrorHandler(response,new ErrorResult(ErrorCode.USER_UNAUTHORIZED));
                return;
            }
            // get jwt token and validate
            final String token = header.split(" ")[1].trim();

            // get user identity and set it on the spring security context
            try {
                User user = accessTokenService.parseJwtToken(token);
                SecurityContextHolder.set("userInfo",user);
                filterChain.doFilter(request, response);
            } catch (AuthException exception) {
                logger.error("casdoor auth exception", exception);
                responseErrorHandler(response,new ErrorResult(ErrorCode.USER_UNAUTHORIZED));
                return;
            }

        } catch (Exception e) {
            logger.error("HttpFilter Error:" + e.getMessage(), e);

            responseErrorHandler(response,new ErrorResult(ErrorCode.USER_UNAUTHORIZED));
            return;
        }
    }



    protected boolean matchesIgnoredPatterns(String path) {
        if (this.properties.getIgnoredUrls() == null) {
            return false;
        }

        for (String pattern : this.properties.getIgnoredUrls()) {
            logger.debug("Matching ignored pattern:" + pattern);
            if (this.pathMatcher.match(pattern, path)) {
                logger.debug("Path " + path + " matches ignored pattern " + pattern);
                return true;
            }
        }
        return false;
    }

    private void responseErrorHandler(HttpServletResponse response, ErrorResult errorResult) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET,DELETE,PUT,OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization,x-ailife-authorization,x-yscloud-saas-clientId,x-yscloud-saas-eid,x-yscloud-saas-uid");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpStatus.OK.value());
        try {
            response.getWriter().write(objectMapper.writeValueAsString(errorResult));
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            logger.error("HttpFilter response error:" + e.getMessage(), e);
        }

    }
}